<template>
    <view class="container">
      <view class="report-preview-area">
        <image 
          v-if="reportImage" 
          :src="reportImage" 
          mode="aspectFit" 
          class="report-image"
        />
        <view v-else class="empty-preview">
          <text class="empty-text">请上传检查报告</text>
        </view>
      </view>
      
      <view class="action-buttons">
        <button class="upload-btn" @click="showUploadOptions">上传报告</button>
        <button 
          class="analyze-btn" 
          :disabled="!reportImage || isAnalyzing" 
          :class="{ 'disabled': !reportImage || isAnalyzing }"
          @click="analyzeReport"
        >现在解读</button>
      </view>
      
      <view v-if="isAnalyzing" class="loading-container">
        <view class="loading-spinner"></view>
        <text class="loading-text">正在解读中...</text>
      </view>
      
      <view class="result-container">
        <view class="result-title">解读结果</view>
        <view class="result-content">
            <span v-html="renderedResult"></span>
        </view>
        </view>
      
      <!-- 上传选项弹窗 -->
      <uni-popup ref="uploadPopup" type="bottom">
        <view class="popup-content">
          <view class="popup-item" @click="chooseImage('camera')">
            <text>拍照上传</text>
          </view>
          <view class="popup-item" @click="chooseImage('album')">
            <text>从相册选择</text>
          </view>
          <view class="popup-item cancel" @click="closePopup">
            <text>取消</text>
          </view>
        </view>
      </uni-popup>
    </view>
  </template>
  
  <script>
  import marked from 'marked';
  import { UPLOAD_FILE } from '@/api/cms';
import { domain } from '@/config';
  
  // 配置 marked 选项
  marked.setOptions({
    breaks: true,       // 将换行转换为 <br>
    sanitize: true,     // 清理危险 HTML
    smartypants: true,  // 自动转换引号、破折号等
    silent: true        // 禁止控制台警告
  });
  
  export default {
    data() {
      return {
        reportImage: '', // 报告图片路径
        analysisResult: '', // 完整的解析结果
        displayedResult: '', // 用于打字效果显示的结果
        isAnalyzing: false, // 是否正在解析
        isTyping: false, // 是否正在打字效果中
        typingSpeed: 30, // 打字效果速度(ms)
        eventSource: null, // SSE 事件源
        typingTimer: null, // 打字效果定时器
        requestTask: null,
        buffer: ''
      }
    },
    computed: {
      // 将 markdown 转换为 HTML
      renderedResult() {
        if (!this.displayedResult) return '';
        
        try {
          // 检测是否为 Markdown 格式
          const isMarkdown = this.isMarkdownContent(this.displayedResult);
          
          if (isMarkdown) {
            return marked.parse(this.displayedResult);
          } else {
            // 纯文本转为简单 Markdown 再渲染
            const markdownText = `# 检查报告解读\n\n${this.displayedResult}`;
            return marked.parse(markdownText);
          }
        } catch (error) {
          // 回退为纯文本显示
          return `<div>${this.displayedResult.replace(/</g, '&lt;')}</div>`;
        }
      }
    },
    methods: {
      // 检测内容是否为 Markdown 格式
      isMarkdownContent(text) {
        // 简单检测是否包含 Markdown 语法
        const markdownPatterns = [
          /^#+ .*$/m,  // 标题
          /\*\*.+?\*\*/,  // 粗体
          /\*.+?\*/,  // 斜体
          /\[.+?\]\(.+?\)/,  // 链接
          /^- .*$/m,  // 无序列表
          /^[0-9]+\. .*$/m,  // 有序列表
          /^>.+$/m,  // 引用
          /`{1,3}[\s\S]*?`{1,3}/  // 代码块
        ];
        
        return markdownPatterns.some(pattern => pattern.test(text));
      },
      
      // 显示上传选项
      showUploadOptions() {
        this.$refs.uploadPopup.open();
      },
      
      // 关闭弹窗
      closePopup() {
        this.$refs.uploadPopup.close();
      },
      
      // 选择图片
      chooseImage(sourceType) {
        this.closePopup();
        
        uni.chooseImage({
          count: 1,
          sourceType: sourceType === 'camera' ? ['camera'] : ['album'],
          success: (res) => {
            this.reportImage = res.tempFilePaths[0];
            // 重置解析结果
            this.analysisResult = '';
            this.displayedResult = '';
          },
          fail: (err) => {
            console.error('选择图片失败', err);
          }
        });
      },
      
      // 解析报告
      analyzeReport() {
        if (!this.reportImage) {
          uni.showToast({
            title: '请先上传检查报告',
            icon: 'none'
          });
          return;
        }
        
        this.isAnalyzing = true;
        this.analysisResult = '';
        this.displayedResult = '';
        this.buffer = '';
        
        // 先上传图片
        uni.uploadFile({
          url: domain + UPLOAD_FILE,
          filePath: this.reportImage,
          name: 'file',
          success: (res) => {
            try {
              const response = JSON.parse(res.data).data;
              console.log('response response',response);
              // 上传成功后，开始SSE连接获取解析结果
              if (response) {
                
                this.connectSSE(response);
              } else {
                throw new Error('未获取到requestId');
              }
            } catch (error) {
              this.isAnalyzing = false;
              uni.showToast({
                title: '解析失败，请重试',
                icon: 'none'
              });
              console.error('解析响应失败', error);
            }
          },
          fail: (err) => {
            this.isAnalyzing = false;   
            uni.showToast({
              title: '上传失败，请重试',
              icon: 'none'
            });
            console.error('上传失败', err);
          }
        });
      },
      
      // 连接SSE获取解析结果
      connectSSE(response) {
        this.isAnalyzing = true;
        this.analysisResult = '';
        this.displayedResult = '';
        this.buffer = '';
        
        try {
          // 获取图片路径并进行URL解码
          const imagePath = response ? response : '';
          console.log('uploadFile1 response :',response);
          if (!imagePath) {
            throw new Error('图片路径为空');
          }
          
          // 创建请求任务
          this.requestTask = wx.request({
            url: domain + '/v1/xcx/ai/checkReport',
            method: 'GET',
            responseType: 'text',
            data: {
              imagePath: imagePath  // 使用解码后的图片路径
            },
            header: {
              'Content-Type': 'application/json',
              'Accept': 'text/event-stream'
            },
            enableChunked: true, // 开启分块传输模式
            success: (res) => {
              if (res.statusCode !== 200) {
                throw new Error(`请求失败: ${res.statusCode}`);
              }
            },
            fail: (err) => {
              console.error('SSE连接错误', err);
              this.isAnalyzing = false;
              
              uni.showToast({
                title: '解读失败，请重试',
                icon: 'none'
              });
            },
            complete: () => {
              // 请求结束时处理残留数据
              if (this.buffer && this.buffer.trim()) {
                this.processEvent(this.buffer.trim());
                this.buffer = '';
              }
              this.isAnalyzing = false;
            }
          });

          // 监听分块数据接收
          this.requestTask.onChunkReceived((res) => {
            const chunk = this.decodeChunk(res.data);
            this.buffer += chunk;
            
            let lastIndex = 0;
            while (true) {
              const eventEndIndex = this.buffer.indexOf('\n\n', lastIndex);
              if (eventEndIndex === -1) break;
              
              const eventData = this.buffer.slice(lastIndex, eventEndIndex).trim();
              lastIndex = eventEndIndex + 2;
              
              if (eventData) {
                this.processEvent(eventData);
              }
            }
            this.buffer = this.buffer.slice(lastIndex);
          });
        } catch (err) {
          console.error('请求失败:', err);
          uni.showToast({ 
            title: '解读失败，请重试', 
            icon: 'none' 
          });
          this.isAnalyzing = false;
        }
      },
      
      // 添加解码方法，与 index.vue 保持一致
      decodeChunk(chunk) {
      if (chunk instanceof ArrayBuffer) {
        // 手动解码 ArrayBuffer 为字符串
        let result = '';
        const uint8Array = new Uint8Array(chunk);
        for (let i = 0; i < uint8Array.length; i++) {
          result += String.fromCharCode(uint8Array[i]);
        }
        return result;
      }
      return chunk;
    },
      
      // 处理SSE事件
      processEvent(eventData) {
        if (!eventData.startsWith('data:')) return;

        const jsonStr = eventData.slice(5).trim();
        if (!jsonStr) return;

        try {
          const data = JSON.parse(jsonStr);
          if (data.content) {
            // 累加内容
            this.analysisResult += data.content;
            
            // 如果当前没有正在进行打字效果，则开始
            if (!this.isTyping) {
              this.startTypingEffect();
            }
          }
        } catch (error) {
          console.error('解析事件数据失败:', error);
        }
      },
      
      // 打字效果
      startTypingEffect() {
        // 清除之前的定时器
        if (this.typingTimer) {
          clearTimeout(this.typingTimer);
        }
        
        this.isTyping = true;
        
        const typeNextChar = () => {
          if (this.displayedResult.length < this.analysisResult.length) {
            this.displayedResult = this.analysisResult.substring(0, this.displayedResult.length + 1);
            this.typingTimer = setTimeout(typeNextChar, this.typingSpeed);
          } else {
            this.isTyping = false;
            
            // 如果分析已完成但还有新内容，继续打字效果
            if (this.displayedResult.length < this.analysisResult.length) {
              this.startTypingEffect();
            }
          }
        };
        
        typeNextChar();
      }
    },
    // 组件销毁时清理资源
    beforeDestroy() {
      if (this.eventSource) {
        this.eventSource.close();
        this.eventSource = null;
      }
      
      if (this.typingTimer) {
        clearTimeout(this.typingTimer);
        this.typingTimer = null;
      }
    }
  }
  </script>
  
  <style lang="scss">
  .container {
    padding: 30rpx;
    display: flex;
    flex-direction: column;
    min-height: 100vh;
    background-color: #f8f8f8;
  }
  
  .report-preview-area {
    width: 100%;
    height: 500rpx;
    background-color: #ffffff;
    border-radius: 16rpx;
    margin-bottom: 30rpx;
    display: flex;
    justify-content: center;
    align-items: center;
    overflow: hidden;
    box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
  }
  
  .report-image {
    width: 100%;
    height: 100%;
  }
  
  .empty-preview {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
  }
  
  .empty-text {
    color: #999999;
    font-size: 28rpx;
  }
  
  .action-buttons {
    display: flex;
    justify-content: space-between;
    margin-bottom: 40rpx;
  }
  
  .upload-btn, .analyze-btn {
    width: 48%;
    height: 80rpx;
    line-height: 80rpx;
    text-align: center;
    border-radius: 40rpx;
    font-size: 28rpx;
    font-weight: bold;
  }
  
  .upload-btn {
    background-color: #ffffff;
    color: #333333;
    border: 1px solid #dddddd;
  }
  
  .analyze-btn {
    background-color: #4a90e2;
    color: #ffffff;
  }
  
  .analyze-btn.disabled {
    background-color: #cccccc;
    color: #ffffff;
  }
  
  .loading-container {
    display: flex;
    flex-direction: column;
    align-items: center;
    margin: 30rpx 0;
  }
  
  .loading-spinner {
    width: 60rpx;
    height: 60rpx;
    border: 4rpx solid #f3f3f3;
    border-top: 4rpx solid #4a90e2;
    border-radius: 50%;
    animation: spin 1s linear infinite;
    margin-bottom: 20rpx;
  }
  
  @keyframes spin {
    0% { transform: rotate(0deg); }
    100% { transform: rotate(360deg); }
  }
  
  .loading-text {
    font-size: 28rpx;
    color: #666666;
  }
  
  .result-container {
    background-color: #ffffff;
    border-radius: 16rpx;
    padding: 30rpx;
    margin-top: 20rpx;
    flex: 1;
    box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
  }
  
  .result-title {
    font-size: 32rpx;
    font-weight: bold;
    color: #333333;
    margin-bottom: 20rpx;
    padding-bottom: 20rpx;
    border-bottom: 1rpx solid #eeeeee;
  }
  
  .result-content {
    font-size: 28rpx;
    color: #333333;
    line-height: 1.6;
  }
  
  /* Markdown 样式 */
  .result-content :deep(.h1),
  .result-content :deep(.h2),
  .result-content :deep(.h3) {
    margin: 32rpx 0 16rpx;
    font-weight: 600;
    color: #222;
  }
  
  .result-content :deep(.h1) { font-size: 40rpx; }
  .result-content :deep(.h2) { font-size: 36rpx; }
  .result-content :deep(.h3) { font-size: 32rpx; }
  
  .result-content :deep(.p) {
    margin: 16rpx 0;     
    white-space: pre-wrap;
    line-height: 1.6; 
  }
  
  .result-content :deep(.strong) { 
    font-weight: bold; 
    color: #222;
  }    
  
  .result-content :deep(.em) { 
    font-style: italic; 
  }       
  
  .result-content :deep(.code) {
    padding: 4rpx 8rpx;
    background: #f5f5f5;
    border-radius: 4rpx;
    font-family: monospace;
    font-size: 24rpx;
    color: #ff6b81;
  }
  
  .result-content :deep(.li) {
    margin: 12rpx 0;
    line-height: 1.6;
  }
  
  .result-content :deep(.a) {
    color: #4a90e2;
    text-decoration: none;
  }
  
  .result-content :deep(.blockquote) {
    margin: 16rpx 0;
    padding: 16rpx 24rpx;
    border-left: 4rpx solid #4a90e2;
    background: #f8f8f8;
    color: #666;
  }
  
  .popup-content {
    background-color: #ffffff;
    border-radius: 16rpx 16rpx 0 0;
    overflow: hidden;
  }
  
  .popup-item {
    height: 100rpx;
    line-height: 100rpx;
    text-align: center;
    font-size: 28rpx;
    color: #333333;
    border-bottom: 1rpx solid #eeeeee;
  }
  
  .popup-item:active {
    background-color: #f5f5f5;
  }
  
  .popup-item.cancel {
    color: #999999;
    margin-top: 10rpx;
  }
  </style>